//
//  ZZKeyboardView.m
//  ExpertApp
//
//  Created by zhangxy on 2017/9/8.
//  Copyright © 2017年 sjhz. All rights reserved.
//

#import "ZZKeyboardView.h"
#import "UIView+Border.h"
#import "ZZCoreTools.h"
#import "ZTextView.h"

#define EmojiViewHeight 216


/**
 *  BottomButtonClickTag ENUM
 */
typedef NS_ENUM(NSInteger, ZZQoneKeyboardType) {
    
    
    /** 普通键盘 */
    ZZQoneKeyboardTypeDefault     = 0,
    /** 表情键盘 */
    ZZQoneKeyboardTypeFaceView    = 1
};


@interface ZZKeyboardView()<UITextViewDelegate,EmojiBoardDelegate>{
    UITapGestureRecognizer *tapRecognizer;
    CGFloat navY;
    
    ZZTopicCommentEntity *tempModel;
    
    
}

@property(nonatomic,strong) UIViewController *curVC;
@property(nonatomic,strong) UIScrollView     *changeView;
@property(nonatomic,strong) ZTextView      *textField;


@property(nonatomic,assign) CGFloat         zc_keyBoardHeight;


/** emjoy布局view */
@property (nonatomic,strong) EmojiBoardView *zc_emojiView;


@end

@implementation ZZKeyboardView

-(instancetype)initWithDelegate:(UIViewController *)delegate changeView:(UIScrollView *)changeView show:(BOOL)isShowKeyboard{
    self = [super init];
    if(self){
        _curVC = delegate;
        _changeView = changeView;
        
        [_curVC.view addSubview:self];
        
        navY = _changeView.frame.origin.y;
        
        [self endEditing:YES];
        
        self.frame = CGRectMake(0, ScreenHeight - NavBarHeight - BottomHeight, ScreenWidth, BottomHeight);
        [self addTopBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
        [self setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
        
        
        
      
        
        UIButton *imgIcon = [UIButton buttonWithType:UIButtonTypeCustom];
        [imgIcon setFrame:CGRectMake(ScreenWidth - 34, BottomHeight/2-12, 24, 24)];
        [imgIcon setImage:[UIImage imageNamed:@"表情1"] forState:0];
        [imgIcon addTarget:self action:@selector(addEmoji:) forControlEvents:UIControlEventTouchUpInside];
        imgIcon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self addSubview:imgIcon];
        
        
        _textField = [[ZTextView alloc] init];
        _textField.frame = CGRectMake(10, 6.5, ScreenWidth - 54, 35);
        //        _textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5);
        _textField.placeholder = @"说说你的看法...";
        _textField.layer.cornerRadius                      = 4.0f;
        _textField.layer.masksToBounds                     = YES;
        _textField.layer.borderColor = UIColorFromRGB(BgLineColor).CGColor;
        _textField.layer.borderWidth = 1.0f;
        _textField.placeholderColor = LIGHT_GRAY_COLOR;
        _textField.font                                    = ListDetailFont;
        _textField.textColor                               = UIColorFromRGB(TextSizeEightColor);
        _textField.returnKeyType                           = UIReturnKeySend;
        _textField.autoresizesSubviews                     = YES;
        _textField.delegate                                = self;
        _textField.textAlignment                           = NSTextAlignmentLeft;
        _textField.autoresizingMask                        = (UIViewAutoresizingFlexibleWidth);
        [_textField setBackgroundColor:[UIColor clearColor]];
        [self addSubview:_textField];
        
        [self handleKeyboard];
        
        
        if(isShowKeyboard){
            [_textField becomeFirstResponder];
        }
        [self createEmojiView];
    }
    return self;
}

-(void)sendMessage{
    if([@"" isEqual:convertToString(_textField.text)]){
        return;
    }
    if(_ResultBlock){
        _ResultBlock(0,convertToString(_textField.text),tempModel);
    }
    
    _textField.text = @"";
    [self textViewDidChange:_textField];
    
    [self hideKeyboard];
}

#pragma mark -- 表情键盘
-(void)createEmojiView{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //添加照相机、相册视图
        CGFloat emojiViewH = EmojiViewHeight;
        
        self->_zc_emojiView=[[EmojiBoardView alloc] initWithBoardHeight:emojiViewH pH:ScreenHeight pW:ScreenWidth];
        self->_zc_emojiView.delegate = self;
        [self->_curVC.view  addSubview:self->_zc_emojiView];
        
        UIView * lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
        lineView2.backgroundColor = UIColorFromRGB(BgLineColor);
        [self->_zc_emojiView addSubview:lineView2];
    });
}

-(void)addEmoji:(UIButton *)btn{
    CGRect ff        = _zc_emojiView.frame;
    if(ff.origin.y != ScreenHeight){
        // 切换键盘
        [_textField becomeFirstResponder];
    }else{
        // 显示键盘
        [self showKeyboardType:ZZQoneKeyboardTypeFaceView];
    }
}

-(void)showKeyboardType:(ZZQoneKeyboardType) type{
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        //隐藏键盘
        [_textField resignFirstResponder];
        CGRect tf        = _changeView.frame;
        CGRect ff        = _zc_emojiView.frame;
        CGRect bf        = self.frame;
        
        
        //显示表情
        if(type==ZZQoneKeyboardTypeFaceView){
            CGFloat emojiViewH = EmojiViewHeight;
            
            _zc_keyBoardHeight = emojiViewH;
            
            ff.origin.x=0;
            ff.origin.y=ScreenHeight - NavBarHeight - _zc_keyBoardHeight;
            _zc_emojiView.frame=ff;
        }
        
        
        [self changeBottomTableFrame];
    } completion:^(BOOL finished) {
        // 回收键盘的手势记得要添加
        [_curVC.view addGestureRecognizer:tapRecognizer];
    }];
}

-(void)hideKeyboard{
    [_textField resignFirstResponder];
    [UIView animateWithDuration:0.25 animations:^{
        _zc_keyBoardHeight = 0;
        
        CGRect ff         = _zc_emojiView.frame;
        ff.origin.y       = ScreenHeight;
        _zc_emojiView.frame  = ff;
        
        [self changeBottomTableFrame];
    }];
}


-(void)changeBottomTableFrame{
    CGRect tf        = _changeView.frame;
    CGRect bf = self.frame;
    
    CGFloat NH = 0;
    CGFloat bh         = BottomHeight + (_textField.frame.size.height-35);
    CGFloat x = tf.size.height-_changeView.contentSize.height;
    
    if (ZC_iPhoneX) {
        NH = NH + 34;  // iphoneX 单独处理34的高度
    }
    if(x > 0){
        if(x<_zc_keyBoardHeight){
            tf.origin.y = NH - (_zc_keyBoardHeight - x)-(bh-BottomHeight);
        }
    }else{
        tf.origin.y   = NH - _zc_keyBoardHeight-(bh-BottomHeight);
    }
    _changeView.frame  = tf;
    
    
    bf.origin.y       = ScreenHeight - bh - _zc_keyBoardHeight - NavBarHeight;// - StatusBarHeight
    bf.size.height    = bh;
    self.frame = bf;
    
    
    
}

/**
 *  表情键盘点击
 *
 *  @param faceTag 表情
 *  @param name    表情
 *  @param itemId  第几个
 */
-(void)onEmojiItemClick:(NSString *)faceTag faceName:(NSString *)name index:(NSInteger)itemId{
    _textField.text=[NSString stringWithFormat:@"%@%@",_textField.text,name];
    [self textViewDidChange:_textField];
}

// 表情键盘执行删除
-(void)emojiAction:(EmojiBoardActionType)action{
    if(action==EmojiActionDel){
        NSString *text = _textField.text;
        NSInteger lenght=text.length;
        if(lenght>0){
            NSInteger end=-1;
            NSString *lastStr= [text substringWithRange:NSMakeRange(lenght-1, 1)];
            if([lastStr isEqualToString:@"]"]){
                NSRange range=[text rangeOfString:@"[" options:NSBackwardsSearch];
                end=range.location;
                NSString *faceStr = [text substringFromIndex:end];
                if([[[ZZCoreTools getCoreTools] allExpressionDict] objectForKey:faceStr]==nil){
                    end = lenght - 1;
                }
            }else{
                end=lenght-1;
            }
            
            text=[text substringToIndex:end];
            _textField.text=text;
            
            [self textViewDidChange:_textField];
        }
    }else if(action==EmojiActionSend){
        [self sendMessage];
    }
}


-(void)setReplyModel:(ZZTopicCommentEntity *)model{
    if(model!=nil){
        [_textField setText:[NSString stringWithFormat:@"@%@ ",model.user_name]];
        tempModel = model;
    }
}

//屏幕点击事件
- (void)didTapAnywhere:(UITapGestureRecognizer *)recognizer {
    [self hideKeyboard];
}


//键盘隐藏
- (void)keyboardWillHide:(NSNotification *)notification {
    float animationDuration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView beginAnimations:@"bottomBarDown" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    CGRect ff         = _zc_emojiView.frame;
    ff.origin.y       = ScreenHeight;
    _zc_emojiView.frame  = ff;
    
    [self changeBottomTableFrame];
    
    [UIView commitAnimations];
    
    
    [_curVC.view removeGestureRecognizer:tapRecognizer];
}



//键盘显示
- (void)keyboardWillShow:(NSNotification *)notification {
    float animationDuration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    CGFloat keyboardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:[curve intValue]];
    [UIView setAnimationDelegate:self];
    // get a rect for the view frame
    
    {
        CGRect tf         = _changeView.frame;
        tf.origin.y       = navY - keyboardHeight;
        _changeView.frame  = tf;
        
        CGRect bf         = self.frame;
        bf.origin.y       = ScreenHeight - NavBarHeight - BottomHeight - keyboardHeight;
        
        self.frame = bf;
    }
    
    // commit animations
    [UIView commitAnimations];
    
    [_curVC.view addGestureRecognizer:tapRecognizer];
}


- (void)handleKeyboard {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)];
    [_curVC.view addGestureRecognizer:tapRecognizer];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""] && tempModel!=nil){
        if([[NSString stringWithFormat:@"@%@",tempModel.user_name]  isEqual:textField.text]){
            _textField.text = @"";
            tempModel = nil;
            return NO;
        }
    }
    return YES;
        
}

#pragma mark 发送监听 UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([@"\n" isEqualToString:text] == YES)
    {
        //        [textView resignFirstResponder];
        
        [self sendMessage];
        return NO;
    }
    
    if ([text isEqualToString:@""] && tempModel!=nil){
        if([[NSString stringWithFormat:@"@%@",tempModel.user_name]  isEqual:_textField.text]){
            _textField.text = @"";
            tempModel = nil;
            return NO;
        }else{
            [self textViewDidChange:_textField];
        }
    }
    return YES;
}



-(void)textViewDidChange:(UITextView *)textView{
    
    
    CGFloat textContentSizeHeight=_textField.contentSize.height;
    if (iOS7) {
        CGRect textFrame=[[_textField layoutManager] usedRectForTextContainer:[_textField textContainer]];
        textContentSizeHeight = textFrame.size.height;
        textContentSizeHeight=textContentSizeHeight+10;
    }
    //发送完成重置
    if(_textField.text==nil || [@"" isEqual:_textField.text]){
        textContentSizeHeight=35;
        [_textField setContentOffset:CGPointMake(0, 0)];
    }
    
    // 判断文字过小
    if(textContentSizeHeight<35){
        textContentSizeHeight=35;
    }
    
    // 已经最大行高了
    if (textContentSizeHeight > [self getTextMaxHeiht] && _textField.frame.size.height >= [self getTextMaxHeiht]) {
        [_textField setContentOffset:CGPointMake(0, textContentSizeHeight-_textField.frame.size.height)];
        return;
    }
    
    
    CGRect footFrame = self.frame;
    CGRect textFrame = _textField.frame;
    
    
    footFrame.origin.y = ScreenHeight - _zc_keyBoardHeight - BottomHeight;
    footFrame.size.height = BottomHeight;
    CGFloat lastHeight = textFrame.size.height;
    textFrame.size.height = 35;
    
    // 计算应该改变多少行高
    if(textContentSizeHeight>35){
        float x=textContentSizeHeight-35;
        if(textContentSizeHeight>[self getTextMaxHeiht]){
            x = [self getTextMaxHeiht] - 35;
        }
        
        footFrame.origin.y=footFrame.origin.y-x-NavBarHeight;
        footFrame.size.height=footFrame.size.height+x;
        textFrame.size.height = textFrame.size.height+x;
    }
    
    // 已经更改过了
    if(lastHeight == textFrame.size.height){
        return;
    }
    
    // 必须是animated YES
    [_textField setContentOffset:CGPointMake(0,textContentSizeHeight-textFrame.size.height) animated:YES];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.frame = footFrame;
        self->_textField.frame = textFrame;
        
        [self changeBottomTableFrame];
    }];
}

-(int)getTextLines{
    CGSize lineSize = [_textField.text sizeWithFont:_textField.font];
    return ceil(_textField.contentSize.height/lineSize.height);
}

-(CGFloat) getTextMaxHeiht{
    CGSize lineSize = [_textField.text sizeWithFont:_textField.font];
    return lineSize.height*6+12;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

